package com.fjec.info.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjec.base.entity.SysAnnex;
import com.fjec.base.mapper.SysAnnexMapper;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.util.DateUtil;
import com.fjec.common.view.InfoRotationVO;
import com.fjec.common.view.RpcReturnPage;
import com.fjec.info.entity.InfoRotation;
import com.fjec.info.mapper.InfoRotationMapper;
import com.fjec.info.service.IInfoRotationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 026.轮播图表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-12-18
 */
@Service
public class InfoRotationServiceImpl extends ServiceImpl<InfoRotationMapper, InfoRotation> implements IInfoRotationService {

    @Resource
    private InfoRotationMapper mapper;

    @Resource
    private SysAnnexMapper annexMapper;

//    @Resource
//    private RedisTemplate redisTemplate;

    @Override
    public List<Map<String, Object>> getInfoRotationByMarkCode(Integer markCode) {
        QueryWrapper<InfoRotation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("MarkCode", markCode)
                .eq("DelFlag", 0)
                .eq("Display", 1)
                .orderByAsc("Sort");
        List<InfoRotation> entityList = mapper.selectList(queryWrapper);
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> tmpMap;
        for (InfoRotation entity : entityList) {
            tmpMap = new HashMap<>();
            tmpMap.put("url", entity.getPicUrl());
            if (entity.getLinked() == 1) {
                tmpMap.put("link", entity.getLinkUrl());
            } else {
                tmpMap.put("link", "");
            }
            mapList.add(tmpMap);
        }
        return mapList;
    }

    @Override
    public RpcReturnPage<InfoRotationVO> rpcGetInfoRotationPage(Page page, Integer markCode, String startTime, String endTime) throws Exception {
        QueryWrapper<InfoRotation> queryWrapper = new QueryWrapper<>();
        if (markCode != null && markCode != 0) {
            queryWrapper.eq("MarkCode", markCode);
        }
        if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
            LocalDateTime sTime = LocalDateTime.of(DateUtil.parseLd(startTime, "yyyy-MM-dd"), LocalTime.MIN);
            LocalDateTime eTime = LocalDateTime.of(DateUtil.parseLd(endTime, "yyyy-MM-dd"), LocalTime.MIN);
            queryWrapper.ge("UpdateTime", sTime)
                    .le("UpdateTime", eTime);
        }
        Page<InfoRotation> entityPage = mapper.selectPage(page, queryWrapper);
        List<InfoRotationVO> viewList = new ArrayList<>();
        for (InfoRotation entity : entityPage.getRecords()) {
            InfoRotationVO view = new InfoRotationVO();
//            view.setSortList(new ArrayList<>());
            BeanUtils.copyProperties(view, entity);
            viewList.add(view);
        }
        RpcReturnPage<InfoRotationVO> result = new RpcReturnPage<>();
        result.setDataList(viewList);
        result.setTotal(entityPage.getTotal());
        return result;
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean rpcSaveOrUpdateInfoRotation(Long id, Integer markCode, String title, Long picId, String picUrl,
                                               Integer linked, String linkUrl, Integer sort, Integer display) {
        boolean result = false;
        InfoRotation entity;
        if (id != null && id != 0L) {
            // 更新
            entity = mapper.selectById(id);
        } else {
            // 新增
            entity = new InfoRotation();
            entity.setDelFlag(0);
            entity.setCreateTime(DateUtil.nowLdt());
        }
        if (entity != null) {
            Long oldPicId = entity.getPicId();
            entity.setMarkCode(markCode);
            entity.setTitle(title);
            entity.setPicId(picId);
            entity.setPicUrl(picUrl);
            entity.setLinked(linked);
            entity.setLinkUrl(linkUrl);
            entity.setSort(sort);
            entity.setDisplay(display);
            Map<String, Object> map = new HashMap<>();
            entity.setBizData(map);
            entity.setUpdateTime(DateUtil.nowLdt());
            result = this.saveOrUpdate(entity);
            // 删除旧图片附件
            if (oldPicId != null && picId != null
                    && oldPicId.longValue() != picId.longValue()) {
                SysAnnex annexEntity = annexMapper.selectById(oldPicId);
                if (annexEntity != null) {
                    if (annexEntity.getDelFlag() != 1L) {
                        annexEntity.setDelFlag(1);
                        annexEntity.setUpdateTime(DateUtil.nowLdt());
                        annexMapper.updateById(annexEntity);
                    }
                }
            }
            // 更新新附件为可用
            if (picId != null) {
                SysAnnex annexEntity = annexMapper.selectById(oldPicId);
                if (annexEntity != null) {
                    if (annexEntity.getDelFlag() != 0L) {
                        annexEntity.setDelFlag(0);
                        annexEntity.setUpdateTime(DateUtil.nowLdt());
                        annexMapper.updateById(annexEntity);
                    }
                }
            }
            // 如果保存的是首页轮播图，更新缓存
//            if (markCode == 1) {
//                redisTemplate.delete("fjec:rotation:mainPage");
//            }
        }
        return result;
    }

    @Override
    public InfoRotationVO rpcGetInfoRotationById(Long id) throws Exception {
        InfoRotation entity = mapper.selectById(id);
        InfoRotationVO view = null;
        if (entity != null) {
            view = new InfoRotationVO();
//            view.setSortList(new ArrayList<>());
            BeanUtils.copyProperties(view, entity);
            // 查询板块现有轮播图排序情况
//            view.setSortList(getInfoRotationByMarkCodeAndSort(entity.getMarkCode()));
        }
        return view;
    }

    @Override
    public List<Map<String, Object>> getInfoRotationByMarkCodeAndSort(Integer markCode) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        QueryWrapper<InfoRotation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DelFlag", 0)
                .eq("Display", 1)
                .eq("MarkCode", markCode)
                .orderByAsc("Sort");
        Map<String, Object> tmpMap;
        List<InfoRotation> sortEntityList = mapper.selectList(queryWrapper);
        for (InfoRotation sortEntity : sortEntityList) {
            tmpMap = new HashMap<>();
            tmpMap.put("title", sortEntity.getTitle());
            tmpMap.put("sort", sortEntity.getSort());
            mapList.add(tmpMap);
        }
        return mapList;
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean rpcDelInfoRotation(Long id) {
        boolean result = false;
        InfoRotation entity = mapper.selectById(id);
        if (entity != null) {
            entity.setDelFlag(1);
            entity.setUpdateTime(DateUtil.nowLdt());
            // 删除图片附件
            SysAnnex annexEntity = annexMapper.selectById(entity.getPicId());
            if (annexEntity != null) {
                if (annexEntity.getDelFlag() != 1L) {
                    annexEntity.setDelFlag(1);
                    annexEntity.setUpdateTime(DateUtil.nowLdt());
                    annexMapper.updateById(annexEntity);
                }
            }
        }
        return result;
    }

    @Override
    @Cacheable(value = "rotation", key = "'fjec:rotation:mainPage'")
    public List<Map<String, Object>> getMainPageRotation() {
        return doGetMainPageRotation();
    }

    @Override
    @CachePut(value = "rotation", key = "'fjec:rotation:mainPage'")
    public List<Map<String, Object>> cacheMainPageRotation() {
        return doGetMainPageRotation();
    }

    private List<Map<String, Object>> doGetMainPageRotation() {
        QueryWrapper<InfoRotation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("MarkCode", 1)
                .eq("DelFlag", 0)
                .eq("Display", 1)
                .orderByAsc("Sort");
        List<InfoRotation> entityList = mapper.selectList(queryWrapper);
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> tmpMap;
        for (InfoRotation entity : entityList) {
            tmpMap = new HashMap<>();
            tmpMap.put("url", entity.getPicUrl());
            if (entity.getLinked() == 1) {
                tmpMap.put("link", entity.getLinkUrl());
            } else {
                tmpMap.put("link", "");
            }
            mapList.add(tmpMap);
        }
        return mapList;
    }
}
